<?php
//
// +---------------------------------------------------------------------------------+
// | Package: EezeeSite Core                                                         |
// +---------------------------------------------------------------------------------+
// | Copyright (C) 2006  EezeeSite Development Team                                  |
// +---------------------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or                   |
// | modify it under the terms of the GNU General Public License                     |
// | as published by the Free Software Foundation; either version 2                  |
// | of the License, or (at your option) any later version.                          |
// |                                                                                 |
// | This program is distributed in the hope that it will be useful,                 |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of                  |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                   |
// | GNU General Public License for more details.                                    |
// |                                                                                 |
// | You should have received a copy of the GNU General Public License               |
// | along with this program; if not, write to the Free Software                     |
// | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. |
// +---------------------------------------------------------------------------------+
// | Author: Mayukh De <mayukhde@gmail.com>                                          |
// +---------------------------------------------------------------------------------+
//

class ESAuthentication
{
    var $auth;
    var $DB;
    var $AJAXResponse;
    var $userID;
    
    function ESAuthentication()
    {
        global $ESDB;
        $this->DB = $ESDB;
        $this->AJAXResponse = new HTML_AJAX_Action();
        $luConf = array(
                       'login'  => array(
                                        'force' => true
                                        ),
                       'session' => array(
                                         'name' => $GLOBALS['ES']['CLIENTCONF']['cookie_name'].'_SESSION'
                                         ),
                       'logout' => array(
                                        'destroy' => true
                                        ),
                       'cookie' => array(
                                        'name'     => $GLOBALS['ES']['CLIENTCONF']['cookie_name'].'_COOKIE',
                                        'path'     => '/',
                                        'domain'   => $_SERVER['HTTP_HOST'],
                                        'lifetime' => 7,
                                        'savedir'  => $GLOBALS['ES']['SESSIONSDIR'],
                                        'secure'   => false,
                                        ),
                       'authContainers' => array(
                                                'users' => array(
                                                                'type'                  => 'DB',
                                                                'loginTimeout'          => 0,
                                                                'expireTime'            => $GLOBALS['ES']['AUTHTIMEOUT']['EXPIRE'],
                                                                'idleTime'              => $GLOBALS['ES']['AUTHTIMEOUT']['IDLE'],
                                                                'updateLastLogin'       => true,
                                                                'allowDuplicateHandles' => false,
                                                                'allowEmptyPasswords'   => false,
                                                                'storage' => array(
                                                                                  'dsn'    => $this->DB->dsn,
                                                                                  'prefix' => ES_TBL_PRE,
                                                                                  'tables' =>  array(
                                                                                                    'users' => array(
                                                                                                                    'fields' => array(
                                                                                                                                     'lastlogin' => 'timestamp',
                                                                                                                                     'is_active' => 'boolean'
                                                                                                                                     ),
                                                                                                                    ),
                                                                                                   ),
                                                                                  'alias'  => array(
                                                                                                   'users'        => 'users',
                                                                                                   'auth_user_id' => 'user_id',
                                                                                                   'is_active'    => 'is_active',
                                                                                                   'handle'       => 'email',
                                                                                                   'passwd'       => 'password',
                                                                                                   'lastlogin'    => 'lastaccess'
                                                                                                   )
                                                                                  )
                                                                )
                                                ),
                       'permContainer'  => array(
                                                'type'    => 'Medium',
                                                'storage' => array(
                                                                  'DB' => array(
                                                                               'dsn'    => $this->DB->dsn,
                                                                               'prefix' => ES_TBL_PRE.ES_LU_PRE
                                                                               )
                                                                  )
                                                )
                       );
        $this->auth =& LiveUser::factory($luConf);
        $this->auth->init();
        if ($this->auth->isLoggedIn()) {
            $this->userID = $this->auth->_auth->propertyValues['auth_user_id'];
        }
        return;
    }
    
    function updateAuthVals($userID = null)
    {
        $userID = ($userID) ? $userID : $this->auth->_auth->propertyValues['auth_user_id'];
        $users = new ESDBOps($this->DB, ES_USERS_TBL);
        $users->resetVars(ES_USERS_TBL);
        $newVals = array(
                        'lastcookie' => $_COOKIE[$GLOBALS['ES']['CLIENTCONF']['cookie_name'].'_SESSION'],
                        'lastip'     => $_SERVER['REMOTE_ADDR']
                        );
        $where = 'user_id = \''.$userID.'\'';
        $users->update($newVals, $where);
        return;
    }
    
    function getUserDetails($data = null)
    {
        if ($data && is_array($data)) {
            if (array_key_exists('uid', $data)) {
                $where = 'user_id = \''.$data['uid'].'\'';
            } elseif (array_key_exists('handle', $data)) {
                $where = 'handle = \''.$data['handle'].'\'';
            } elseif (array_key_exists('email', $data)) {
                $where = 'email = \''.$data['email'].'\'';
            } else {
                return null;
            }
        } else {
            if ($this->auth->_auth) {
                $where = 'user_id = \''.$this->auth->_auth->propertyValues['auth_user_id'].'\'';
            } else {
                return null;
            }
        }
        $user = new ESDBOps($this->DB, '');
        $user->sql['details'] = array(
                                     'select' => 'user_id, email, handle, lastaccess, user_group',
                                     'from'   => ES_USERS_TBL,
                                     'where'  => $where.' AND is_active = \'1\''
                                     );
        $userDetails = $user->select('details');
        return $userDetails[0];
    }
    
    function newPassword($userDetails)
    {
        global $ESMail;
        $pass = Text_Password::create(8, 'unpronounceable', 'alphanumeric');
        if (!is_object($ESMail)) {
            $ESMail = &Mail::factory(strtolower($GLOBALS['ES']['EMAILPROTOCOLS']['MAIL']), $GLOBALS['ES']['EMAILSETTINGS']['MAIL']);
        }
        $usersDB = new ESDBOps($this->DB, ES_USERS_TBL);
        $usersDB->resetVars(ES_USERS_TBL);
        $newVals = array(
                        'password' => md5($pass)
                        );
        $where = 'user_id = \''.$userDetails['user_id'].'\'';
        $usersDB->update($newVals, $where);
        $body = sprintf($GLOBALS['ES']['LANG']['EMAILER']['NEWPASSWORD'], $userDetails['handle'], $pass, $GLOBALS['ES']['CLIENTCONF']['site_title'], ES_BASE_URL);
        return $body;//temp
        $recipients = $userDetails['email'];
        $headers['From']    = $GLOBALS['ES']['CLIENTCONF']['primary_email'];
        $headers['To']      = $userDetails['email'];
        $headers['Subject'] = 'Password reminder/change';
        $ESMail->send($recipients, $headers, $body);
        return;
    }
    
    function authFailMessage()
    {
        $authFailMsg = array(
                            '-1' => $GLOBALS['ES']['LANG']['AUTH']['FAIL']['IDLED'],
                            '-2' => $GLOBALS['ES']['LANG']['AUTH']['FAIL']['SESSIONOUT'],
                            '-3' => $GLOBALS['ES']['LANG']['AUTH']['FAIL']['INACTIVE'],
                            '-9' => $GLOBALS['ES']['LANG']['AUTH']['FAIL']['FAIL']
                            );
        $message = (array_key_exists($this->auth->_status, $authFailMsg)) ? $authFailMsg[$this->auth->_status] : null;
        return $message;
    }    
}

?>